package jmu.wj.controller;

import jmu.wj.mapper.UserMapper;
import jmu.wj.pojo.User;
import jmu.wj.service.UserService;
import jmu.wj.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author jxxyw
 */
@RestController
//允许跨域
@CrossOrigin
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 处理登录
     */
    @RequestMapping("login")
    public Map<String, Object> login(@RequestBody User user){
        Map<String, Object> map =new HashMap<>();
        try{
            User user1=userService.login(user);
            map.put("state",true);
            map.put("msg","登录成功！");
            map.put("user",user1);
        }catch (Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","登录失败！"+e.getMessage());
        }
        return map;
    }
    /**
     * 处理注册方法
     */
    @RequestMapping("register")
    public Map<String, Object> register(@RequestBody User user,String code,HttpServletRequest request){
        log.info("用户信息:[{}]",user.toString());
        log.info("用户输入的验证码信息:[{}]",code);
        Map<String, Object> map =new HashMap<>();
        try{
        String key= (String)request.getServletContext().getAttribute("code");
        if(key.equalsIgnoreCase(code)){
            userService.register(user);
            map.put("state",true);
            map.put("msg","注册成功！");
        }else {
            throw new RuntimeException("验证码错误！");
        }
        }
        catch (Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","注册失败！"+e.getMessage());
        }
        return map;
    }
    /**
     *生成验证码图片
     */
    @GetMapping("getImage")
    public String getImageCode(HttpServletRequest request) throws IOException {


        //使用工具类生成验证码
        String code= VerifyCodeUtils.generateVerifyCode(4);
        //将验证码放入servletContext作用域中
        request.getServletContext().setAttribute("code",code);
        //将图片转为base64
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(120,30,byteArrayOutputStream,code);
        return "data:image/png;base64,"+Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());

    }
}
